﻿/*********************************************************
 * 开发人员：小兵
 * 创建时间：2012-9-25 15:34:00
 * 描述说明：
 * 
 * 更改历史：
 * 
 * *******************************************************/
namespace Mozlite.Components
{
    using System;
    using System.Web;
    using System.Data;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Mozlite.Data;
    using System.IO;

    /// <summary>
    /// 文件存储清理后台服务。
    /// </summary>
    public class FileStorageTask : TaskBase
    {
        /// <summary>
        /// 2小时。
        /// </summary>
        public override int Delay
        {
            get { return 2 * Consts.HourSeconds; }
        }
        /// <summary>
        /// 执行清理文件。
        /// </summary>
        public override void Execute()
        {
            if(!DeleteDbFiles())
                return;
            
            var root = new DirectoryInfo( FileStorages.GetUserFilePath());
            if(!root.Exists)
                return;

            var files = LoadDbFiles();
            foreach(var file in root.GetFiles("*", SearchOption.AllDirectories)){
                if(files.Contains(Path.GetFileNameWithoutExtension(file.Name).ToLower()))
                    continue;
                file.Delete();
            }

            var dirs = new List<string>();
            foreach(var dir in root.GetDirectories("*", SearchOption.AllDirectories))
            {
                if(dir.GetFiles("*", SearchOption.AllDirectories).Length > 0)
                    continue;
                dirs.Add(dir.FullName);
            }

            foreach(var dir in dirs)
            {
                if(Directory.Exists(dir))
                    Directory.Delete(dir, true);
            }
        }

        private static List<string> LoadDbFiles() {
            var files = new List<string>();
            using(var reader = Database.ExecuteReader("SELECT MD5 FROM moz_filestorages")) {
                while(reader.Read())
                    files.Add(reader.GetString(0).ToLower());
                reader.Close();
            }
            return files;
        }

        private static bool DeleteDbFiles() {
            return Database.ExecuteNonQuery(@"DELETE FROM moz_filestorages WHERE StorageID NOT IN(SELECT StorageID FROM moz_users_files);");
        }
    }
}
